package co.com.colombiamovil.imeiservice.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import org.apache.commons.io.FileUtils;

import co.com.colombiamovil.imeiservice.vo.BdoNegativaHistVO;

public class ArchivosEIRUtil {
	// private static final Calendar calendar = Calendar.getInstance(new Locale(
	// "es", "CO"));
	private static Locale locale = new Locale("es", "CO");

	/**
	 * 
	 * 
	 * Metodo que crea el archivo para envio a EIR. con el siguiente formato:<br/>
	 * <br/>
	 * <br/>
	 * <br/>
	 * CRE:EQU,777777221234580,123467,5,,20050524,"Added by organisation X",
	 * 143000;<br/>
	 * <br/>
	 * C1:00000; This shows a create command has been successfully executed,
	 * adding a range of 10 equipment items to list 5 as follows: <br/>
	 * The IMEI for the first item in the range is 77777722123458 (the spare
	 * digit, 0, at the end of the IMEI is ignored). <br/>
	 * The end serial number is set to the number of the last equipment item in
	 * the range (123467). <br/>
	 * The SVN is not significant (internally, Airguard sets the SVN to 0F). <br/>
	 * The date associated with the record is 24th May 2005. <br/>
	 * The comment indicates that organisation X added the range. <br/>
	 * The new range was requested at 2:30pm.
	 * 
	 * DEL:EQU,<IMEI>,<end serial number>,<equipment
	 * list>,[<SVN>],[<date>][,"<comment>"][,<time>];<br/>
	 * Success confirmation <br/>
	 * C1:00000;<br/>
	 * Failure confirmation <br/>
	 * C1:<error number>,<error text>;<br/>
	 * Example <br/>
	 * DEL:EQU,777777221234580,123467,4,,20050525,"Deletion requested by X",
	 * 144000;<br/>
	 * C1:00000;<br/>
	 * This shows a delete command has been successfully executed, removing a
	 * range of 10 equipment items from list 4, as follows: <br/>
	 * The IMEI for the first item in the range is 77777722123458 (the spare
	 * digit, 0, at the end of the IMEI is ignored). <br/>
	 * The end serial number is set to the number of the last equipment item in
	 * the range (123467). <br/>
	 * If list 4 is an AICH nominated list, Airguard passes the date (20050525)
	 * comment ("Deletion requested by X") and time (144000) to the AICH,
	 * otherwise it does not use them.<br/>
	 * 
	 * 
	 * @author: Freddy Lemus - IT
	 * @since IMEIServiceStandAlong-v1.1_28/11/2011
	 * 
	 * @param listHistVOs
	 * @param idInstancia
	 * @throws Exception
	 */
	public static void crearArchiEnvio(List<BdoNegativaHistVO> listHistVOs,
			String idInstancia) throws Exception {
		IConstantes.log.info("[" + idInstancia
				+ "] [ArchivosEIRUtil.crearArchiEnvio] Inicio ");

		File archivoMod = null;
		FileWriter fw = null;
		int lineas = 0;

		String fileFecha = getFecha();

		String fileHora = getHora();

		IConstantes.log.info("[" + idInstancia
				+ "] [ArchivosEIRUtil.crearArchiEnvio] nameFile " + fileFecha);
		archivoMod = new File(getNombreFile());

		try {

			if (!listHistVOs.isEmpty()) {
				fw = new FileWriter(archivoMod);
				PrintWriter pw = new PrintWriter(fw, true);
				for (BdoNegativaHistVO bdoNegativaHistVO : listHistVOs) {

					pw.print(IConstantes.constantes.getPropiedad("file.CRE"));
					pw.print(IConstantes.constantes
							.getPropiedad("file.separator"));
					pw.print(bdoNegativaHistVO.getImei());
					pw.print(IConstantes.constantes
							.getPropiedad("file.separator"));
					pw.print(bdoNegativaHistVO.getImei().toString()
							.substring(8, 14));
					pw.print(IConstantes.constantes
							.getPropiedad("file.separator"));
					pw.print(IConstantes.constantes
							.getPropiedad("file.equipment.list"));
					pw.print(IConstantes.constantes
							.getPropiedad("file.separator"));
					pw.print(IConstantes.constantes.getPropiedad("file.svn"));
					pw.print(IConstantes.constantes
							.getPropiedad("file.separator"));
					pw.print(fileFecha);
					pw.print(IConstantes.constantes
							.getPropiedad("file.separator"));
					pw.print(IConstantes.constantes.getPropiedad("file.reason"));
					pw.print(IConstantes.constantes
							.getPropiedad("file.separator"));
					pw.print(fileHora);
					pw.print(IConstantes.constantes
							.getPropiedad("file.endLine"));
					pw.println();

					lineas++;

				}
			} else {
				IConstantes.log
						.info("["
								+ idInstancia
								+ "] [ArchivosEIRUtil.crearArchiEnvio] No existen registro para enviar a EIR ");
			}
		} catch (Exception e) {
			IConstantes.log.error(
					"[" + idInstancia
							+ "] [ArchivosEIRUtil.crearArchiEnvio] Exception "
							+ e.getMessage(), e);
			throw e;
		} finally {
			if (fw != null) {
				fw.close();
			}
			IConstantes.log
					.info("["
							+ idInstancia
							+ "] [ArchivosEIRUtil.crearArchiEnvio] finally Total lineas archivo lineas="
							+ lineas);
		}

	}

	/**
	 * 
	 * 
	 * Metodo para ....
	 * 
	 * @author: Freddy Lemus - IT
	 * @since IMEIServiceStandAlone-v1.1_3/12/2011
	 * 
	 *        Modified By: Freddy Lemus - IT
	 * 
	 *        {@link package.class#member}
	 * 
	 * @return
	 */
	private static String getNombreFile() {
		StringBuffer buffer = new StringBuffer();
		buffer.append(IConstantes.ABSOLUTE_PATH
				+ IConstantes.RUTA_LOCAL_FTP_TEMP);
		buffer.append(File.separator.toString());
		buffer.append(IConstantes.FILE_NOM_INIC);
		buffer.append(getFecha());
		buffer.append(getHora());
		buffer.append(IConstantes.PUNTO);
		buffer.append(IConstantes.FILE_EXTENSION_DAT);

		return buffer.toString();
	}

	/**
	 * 
	 * 
	 * Metodo para ....
	 * 
	 * @author: Freddy Lemus - IT
	 * @since IMEIServiceStandAlone-v1.1_3/12/2011
	 * 
	 *        Modified By: Freddy Lemus - IT
	 * 
	 *        {@link package.class#member}
	 * 
	 * @return
	 */
	private static String getHora() {
		// StringBuffer buffer = new StringBuffer();
		// String HOUR = "" + calendar.get(Calendar.HOUR);
		// if (HOUR.length() == 1) {
		// buffer.append("0" + HOUR);
		// } else {
		// buffer.append(HOUR);
		// }
		//
		// String MINUTE = "" + calendar.get(Calendar.MINUTE);
		// if (MINUTE.length() == 1) {
		// buffer.append("0" + MINUTE);
		// } else {
		// buffer.append(MINUTE);
		// }
		//
		// String SECOND = "" + calendar.get(Calendar.SECOND);
		// if (SECOND.length() == 1) {
		// buffer.append("0" + SECOND);
		// } else {
		// buffer.append(SECOND);
		// }
		//
		// return buffer.toString();
		SimpleDateFormat dateFormat = new SimpleDateFormat("HHmmSS", locale);
		return dateFormat.format(new Date());
	}

	/**
	 * 
	 * 
	 * Metodo que arma la fecha en el formato YYYYMMSS
	 * 
	 * @author: Freddy Lemus - IT
	 * @since IMEIServiceStandAlone-v1.1_3/12/2011
	 * 
	 *        Modified By: Freddy Lemus - IT
	 * 
	 *        {@link package.class#member}
	 * 
	 * @return
	 */
	private static String getFecha() {
		// StringBuffer buffer = new StringBuffer();
		// buffer.append(calendar.get(Calendar.YEAR));
		// String month = "" + (calendar.get(Calendar.MONTH) + 1);
		// if (month.length() == 1) {
		// buffer.append("0" + month);
		// } else {
		// buffer.append(month);
		// }
		// String date = "" + calendar.get(Calendar.DATE);
		// if (date.length() == 1) {
		// buffer.append("0" + date);
		// } else {
		// buffer.append(date);
		// }
		// return buffer.toString();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", locale);
		return dateFormat.format(new Date());
	}

	public static void borrarArchiEnvio(List<BdoNegativaHistVO> listHistVOs,
			String idInstancia) {
		// TODO Auto-generated method stub

	}

	/**
	 * 
	 * 
	 * Metodo encargado de mover los archivos EIR creados, a la carpeta de
	 * enviados
	 * 
	 * @author: Freddy Lemus - IT
	 * @since IMEIServiceStandAlone-v1.1_3/12/2011
	 * 
	 */
	public static void moverFileEIR() {
		String extensiones[] = { IConstantes.FILE_EXTENSION_DAT };
		try {
			File dirOrigen = new File(IConstantes.ABSOLUTE_PATH
					+ IConstantes.RUTA_LOCAL_FTP_TEMP);
			File dirDestino = new File(IConstantes.ABSOLUTE_PATH
					+ IConstantes.RUTA_LOCAL_ENVIO_ENVIADOS);
			for (Iterator<File> it = FileUtils.iterateFiles(dirOrigen,
					extensiones, false); it.hasNext();) {
				File arch = (File) it.next();
				FileUtils.moveFileToDirectory(arch, dirDestino, false);
			}
		} catch (IOException e) {
			IConstantes.log.error(
					"[ArchivosEIRUtil] [moverFileEIR] " + e.getMessage(), e);
		}
	}

}
